package club.kingyin.commons.utils;

import java.math.BigDecimal;

public class SizeUtils {

    private static final String[] UNIT = {" B"," KB"," MB"," GB"," TB"};
    private static final int UNIT_SIZE = 1024;
    private static final double PRECISION = 0.05;

    public enum SizeUnit {
        B,KB,MB,GB,TB;
    }


    public static String changeSize(double bs) {
        int count = 0;
        while ((bs - UNIT_SIZE) > PRECISION) {
            bs/=UNIT_SIZE;
            count++;
        }
        return new BigDecimal(bs).setScale(2,BigDecimal.ROUND_UP).doubleValue()+UNIT[count];
    }

    public static boolean checkFileSize(Long len, int size, SizeUnit unit) {
        double fileSize = 0;
        if (unit == SizeUnit.B) {
            fileSize = (double) len;
        } else if (unit == SizeUnit.KB) {
            fileSize = (double) len / 1024;
        } else if (unit == SizeUnit.MB) {
            fileSize = (double) len / 1048576;
        } else if (unit == SizeUnit.GB) {
            fileSize = (double) len / 1073741824;
        }
        else if (unit == SizeUnit.TB) {
            fileSize = (double) len / 1073741824 / 1024;
        }
        if (fileSize > size) {
            return false;
        }
        return true;
    }

}
